<template>
	<view class="page" :style="loading ? 'opacity: 0;' : 'opacity: 1;'">
		<!--  v-model="dataList" @query="queryList" -->
		<pageTxt>
			<z-paging ref="paging" :paging-style="{ 'background-color': '#f7f7f7', height: '100%', width: '100%' }">
				<!-- 头部 -->
				<template slot="top">
					<view class="navbar-box">
						<u-navbar title="新增合同" :autoBack="true" :fixed="false"></u-navbar>
					</view>
				</template>
				<view class="add-content ios">
					<u--form labelPosition="top" :model="formData" ref="uForm" labelWidth="auto">
						<view class="form-box">
							<u-form-item labelPosition="top" labelWidth="100%" required label="合同类型" borderBottom @click="showSelect('typeListShow')">
								<u-input
									:value="formData.type_item.name"
									disabled
									disabledColor="#ffffff"
									placeholder="请选择合同类型"
									border="none"
									suffixIcon="arrow-right"
								></u-input>
							</u-form-item>
							<u-form-item labelPosition="top" labelWidth="100%" required label="项目名称" borderBottom @click="showSelect('projectListShow')">
								<u-input
									:value="formData.project_item.project_name"
									disabled
									disabledColor="#ffffff"
									placeholder="请选择项目名称"
									border="none"
									suffixIcon="arrow-right"
								></u-input>
							</u-form-item>
							<u-form-item labelPosition="top" labelWidth="100%" required label="签约主体" borderBottom @click="showSelect('companyListShow')">
								<u-input
									:value="formData.signing_company_item.account_name"
									disabled
									disabledColor="#ffffff"
									placeholder="请选择签约主体"
									border="none"
									suffixIcon="arrow-right"
								></u-input>
							</u-form-item>
							<u-form-item
								labelPosition="top"
								labelWidth="100%"
								required
								label="合同开工日期"
								borderBottom
								@click="showSelect('contractCommencementDateShow')"
								v-if="formData.type_item.id == 1 || formData.type_item.id == 3"
							>
								<u-input
									:value="formData.contract_commencement_date"
									disabled
									disabledColor="#ffffff"
									placeholder="请选择合同开工日期"
									border="none"
									suffixIcon="arrow-right"
								></u-input>
							</u-form-item>
							<u-form-item
								labelPosition="top"
								labelWidth="100%"
								required
								label="合同完工日期"
								borderBottom
								@click="showSelect('contractCompletionDateShow')"
								v-if="formData.type_item.id == 1 || formData.type_item.id == 3"
							>
								<u-input
									:value="formData.contract_completion_date"
									disabled
									disabledColor="#ffffff"
									placeholder="请选择合同完工日期"
									border="none"
									suffixIcon="arrow-right"
								></u-input>
							</u-form-item>
							<u-form-item
								labelPosition="top"
								labelWidth="100%"
								required
								label="合同工期"
								borderBottom
								v-if="formData.type_item.id == 1 || formData.type_item.id == 3"
							>
								<u-input
									:value="formData.contract_duration_days"
									disabled
									disabledColor="#ffffff"
									color="#c8c9cc"
									placeholder="请选择合同日期"
									border="none"
								></u-input>
								<template v-slot:right>
									<view class="unit">天</view>
								</template>
							</u-form-item>
							<u-form-item labelPosition="top" labelWidth="100%" required label="合同签约日期" borderBottom>
								<picker mode="date" :value="formData.signing_date" @change="signingDateChange">
									<u-input
										:value="formData.signing_date"
										disabled
										disabledColor="#ffffff"
										placeholder="请选择合同签约日期"
										border="none"
										suffixIcon="arrow-right"
									></u-input>
								</picker>
							</u-form-item>
							<u-form-item labelPosition="top" labelWidth="100%" required label="签约金额" borderBottom>
								<u-input
									:value="formData.contract_price"
									disabledColor="#ffffff"
									disabled
									color="#c8c9cc"
									placeholder="请输入签约金额"
									border="none"
									v-if="formData.type_item.id == 1 && Number(formData.discount_amount) != 0"
								></u-input>
								<u-input
									v-model="formData.contract_price"
									@input="inputFunc($event, 'contract_price')"
									type="number"
									placeholder="请输入签约金额"
									border="none"
									v-else
								></u-input>
								<template v-slot:right>
									<view class="unit">元</view>
								</template>
							</u-form-item>
							<u-form-item labelPosition="top" labelWidth="100%" required label="首期款金额" borderBottom v-if="formData.type_item.id == 1">
								<u-input
									v-model="formData.down_payment"
									@input="inputFunc($event, 'down_payment')"
									@change="jsWkFunc"
									placeholder="请输入首期款金额"
									type="number"
									border="none"
								></u-input>
								<template v-slot:right>
									<view class="unit">元</view>
								</template>
							</u-form-item>
							<u-form-item labelPosition="top" labelWidth="100%" required label="进度款金额" borderBottom v-if="formData.type_item.id == 1">
								<u-input
									v-model="formData.progress_payment"
									@input="inputFunc($event, 'progress_payment')"
									@change="jsWkFunc"
									placeholder="请输入进度款金额"
									type="number"
									border="none"
								></u-input>
								<template v-slot:right>
									<view class="unit">元</view>
								</template>
							</u-form-item>

							<u-form-item labelPosition="top" labelWidth="100%" required label="尾款金额" borderBottom v-if="formData.type_item.id == 1">
								<u-input :value="formData.balance_payment" disabled disabledColor="#ffffff" placeholder="请输入尾款金额" color="#c8c9cc" border="none"></u-input>
								<template v-slot:right>
									<view class="unit">元</view>
								</template>
							</u-form-item>
							<u-form-item labelPosition="top" labelWidth="100%" label="报价金额" borderBottom v-if="formData.type_item.id == 1">
								<u-input :value="formData.system_quotation" disabled disabledColor="#ffffff" placeholder="请输入报价金额" color="#c8c9cc" border="none"></u-input>
								<template v-slot:right>
									<view class="unit">元</view>
								</template>
							</u-form-item>
							<u-form-item labelPosition="top" labelWidth="100%" label="优惠金额" borderBottom v-if="formData.type_item.id == 1">
								<u-input :value="formData.discount_amount" disabled disabledColor="#ffffff" placeholder="请输入优惠金额" color="#c8c9cc" border="none"></u-input>
								<template v-slot:right>
									<view class="unit">元</view>
								</template>
							</u-form-item>
							<u-form-item
								labelPosition="top"
								labelWidth="100%"
								label="关联定金合同"
								borderBottom
								@click="showSelect('DJcontractListShow')"
								v-if="formData.type_item.id == 1"
							>
								<u-input
									:value="formData.earnest_money_contract_item.contract_number"
									disabled
									disabledColor="#ffffff"
									:placeholder="DJcontractList[0].length == 0 ? '无数据' : '请选择关联定金合同'"
									border="none"
									suffixIcon="arrow-right"
								></u-input>
							</u-form-item>
							<u-form-item labelPosition="top" labelWidth="100%" label="已付金额" borderBottom v-if="formData.type_item.id == 1">
								<u-input :value="dataObj.paid_amount" disabled disabledColor="#ffffff" placeholder="请输入已付金额" color="#c8c9cc" border="none"></u-input>
								<template v-slot:right>
									<view class="unit">元</view>
								</template>
							</u-form-item>

							<u-form-item labelPosition="top" labelWidth="100%" label="签约备注" borderBottom>
								<u--textarea
									disableDefaultPadding
									v-model="formData.remark"
									border="none"
									placeholder="签约备注"
									:placeholderStyle="{ fontSize: '13.5px', color: '#BFC4CC' }"
								></u--textarea>
							</u-form-item>
							<u-form-item labelPosition="top" labelWidth="100%" required label="合同附件">
								<file-upload
									:count="1"
									:type="4"
									v-if="fileUploadShow"
									:typeList="['zip', 'ppt', 'ppsx', 'pptx', 'pdf']"
									@afterRead="afterRead($event, 'contract_file')"
									@delete="deletePic($event, 'contract_file')"
								></file-upload>
							</u-form-item>
							<u-form-item labelPosition="top" labelWidth="100%" :required="formData.type_item.id == 1" label="报价单">
								<file-upload
									:count="1"
									:type="4"
									v-if="fileUploadShow"
									:typeList="['ppt', 'xls', 'pdf', 'doc', 'docx', 'xlsx']"
									@afterRead="afterRead($event, 'quotation_file')"
									@delete="deletePic($event, 'quotation_file')"
								></file-upload>
							</u-form-item>
							<u-form-item labelPosition="top" labelWidth="100%" :required="formData.type_item.id == 1" label="利润单">
								<file-upload
									:count="1"
									:type="4"
									v-if="fileUploadShow"
									:typeList="['ppt', 'xls', 'pdf', 'doc', 'docx', 'xlsx']"
									@afterRead="afterRead($event, 'profit_statement_file')"
									@delete="deletePic($event, 'profit_statement_file')"
								></file-upload>
							</u-form-item>
							<u-form-item labelPosition="top" labelWidth="100%" :required="formData.type_item.id == 1" label="工程量清单">
								<file-upload
									:count="1"
									:type="4"
									v-if="fileUploadShow"
									:typeList="['ppt', 'xls', 'pdf', 'doc', 'docx', 'xlsx']"
									@afterRead="afterRead($event, 'cost_list_file')"
									@delete="deletePic($event, 'cost_list_file')"
								></file-upload>
							</u-form-item>
						</view>
					</u--form>
				</view>
				<view class="footer ios">
					<u-button
						text="提交"
						@click="submit"
						customStyle="width: 702rpx;height: 88rpx;background: #3B75FF;border-radius: 16rpx;font-weight: 500;font-size: 28rpx;color: #FFFFFF;margin:20rpx 24rpx;"
					></u-button>
				</view>
			</z-paging>
		</pageTxt>

		<!-- 合同类型 -->
		<u-picker
			:show="typeListShow"
			:columns="typeList"
			keyName="name"
			@confirm="confirm($event, 'type_item')"
			closeOnClickOverlay
			@close="close"
			@cancel="close"
			confirmColor="#3B75FF"
		></u-picker>
		<!-- 项目列表 -->
		<u-picker
			:show="projectListShow"
			:columns="projectList"
			keyName="project_name"
			@confirm="confirm($event, 'project_item')"
			closeOnClickOverlay
			@close="close"
			@cancel="close"
			confirmColor="#3B75FF"
		></u-picker>
		<!-- 签约主体 -->
		<u-picker
			:show="companyListShow"
			:columns="companyList"
			keyName="account_name"
			@confirm="confirm($event, 'signing_company_item')"
			closeOnClickOverlay
			@close="close"
			@cancel="close"
			confirmColor="#3B75FF"
		></u-picker>
		<!-- 合同开工日期 -->
		<u-calendar
			:show="contractCommencementDateShow"
			mode="single"
			@confirm="confirm($event, 'contract_commencement_date', 'date')"
			color="#3B75FF"
			closeOnClickOverlay
			:minDate="dateStart"
			:monthNum="12"
			:defaultDate="dateStart"
			@close="close"
		></u-calendar>
		<!-- 合同完工日期 -->
		<u-calendar
			:show="contractCompletionDateShow"
			mode="single"
			@confirm="confirm($event, 'contract_completion_date', 'date')"
			color="#3B75FF"
			closeOnClickOverlay
			:minDate="dateEnd"
			:monthNum="12"
			:defaultDate="dateEnd"
			@close="close"
		></u-calendar>
		<!-- 定金合同 -->
		<u-picker
			:show="DJcontractListShow"
			:columns="DJcontractList"
			keyName="contract_number"
			@confirm="confirm($event, 'earnest_money_contract_item')"
			closeOnClickOverlay
			@close="close"
			@cancel="close"
			confirmColor="#3B75FF"
		></u-picker>

		<!-- 跳转优惠 -->
		<u-modal
			:show="yhShow"
			title="提示"
			content="优惠已超出权限，是否跳转申请优惠?"
			confirmColor="#3B75FF"
			@close="close"
			@cancel="close"
			@confirm="yhSubmit"
			showCancelButton
			closeOnClickOverlay
		></u-modal>
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
export default {
	data() {
		return {
			dataObj: '',
			dateStart: '',
			dateEnd: '',
			loading: false,
			formData: {
				type_item: '',
				project_item: '',
				signing_company_item: '',
				contract_commencement_date: '',
				contract_completion_date: '',
				contract_duration_days: '',
				signing_date: '',
				contract_price: '',
				down_payment: '',
				progress_payment: '',
				balance_payment: '',
				system_quotation: '',
				discount_amount: '',
				earnest_money_contract_item: '',
				remark: '',
				contract_file: [],
				quotation_file: [],
				profit_statement_file: [],
				cost_list_file: []
			},
			// 合同类型
			typeListShow: false,
			typeList: [
				[
					{
						name: '施工合同',
						id: 1
					},
					{
						name: '勘场合同',
						id: 2
					},
					{
						name: '增减项合同',
						id: 3
					},
					{
						name: '定金合同',
						id: 4
					}
				]
			],
			// 项目列表
			projectListShow: false,
			projectList: [],
			// 签约主体
			companyListShow: false,
			companyList: [],
			// 合同开工日期
			contractCommencementDateShow: false,
			// 合同完工日期
			contractCompletionDateShow: false,
			// 合同签约日期
			signingDateShow: false,
			// 定金合同
			DJcontractListShow: false,
			DJcontractList: [[]],
			yhShow: false,
			fileUploadShow: true
		};
	},
	onLoad(e) {
		switch (e.activeName) {
			case 2:
				this.formData.type_item = {
					name: '勘场合同',
					id: 2
				};
				break;
			case 3:
				this.formData.type_item = {
					name: '增减项合同',
					id: 3
				};
				break;
			case 4:
				this.formData.type_item = {
					name: '定金合同',
					id: 4
				};
				break;
			default:
				e.activeName = 1;
				this.formData.type_item = {
					name: '施工合同',
					id: 1
				};
		}
		this.selectProjectList(e.activeName);
		this.getList();

		const d = new Date();
		const year = d.getFullYear();
		let month = d.getMonth() + 1;
		month = month < 10 ? `0${month}` : month;
		const date = d.getDate() + 1;
		this.dateStart = `${year}-${month}-${date}`;
	},
	methods: {
		inputFunc(e, name) {
			console.log(e, name);
			this.$nextTick(() => {
				this.formData[name] = this.$inputFunc(e);
				console.log(this.formData[name]);
			});
		},
		signingDateChange(e) {
			this.formData.signing_date = e.detail.value;
		},
		showSelect(type) {
			if (type == 'projectListShow' && !this.projectList[0].length) {
				this.$refs.uToast.show({
					message: '暂无可选项目'
				});
				return;
			}
			if (type == 'contractCompletionDateShow') {
				if (!this.formData.contract_commencement_date) {
					this.$refs.uToast.show({
						message: '请先选择开工日期'
					});
					return;
				}
			}
			if (type == 'DJcontractListShow') {
				if (this.DJcontractList[0].length == 0) return;
			}
			this[type] = true;
		},
		close() {
			this.typeListShow = false;
			this.projectListShow = false;
			this.companyListShow = false;
			this.contractCommencementDateShow = false;
			this.contractCompletionDateShow = false;
			this.signingDateShow = false;
			this.DJcontractListShow = false;
			this.yhShow = false;
		},
		async confirm(e, type, date) {
			console.log(e, type, 'confirm');
			if (date) {
				this.formData[type] = e[0];
				if (type == 'contract_commencement_date') {
					let date = new Date(e[0]);
					date.setDate(date.getDate() + 1);
					let year = date.getFullYear();
					let month = String(date.getMonth() + 1).padStart(2, '0');
					let day = String(date.getDate()).padStart(2, '0');
					this.dateEnd = `${year}-${month}-${day}`;
				}
				if (type == 'contract_completion_date') {
					this.dateChangeFunc();
				}
			} else {
				this.formData[type] = e.value[0];
				if (type == 'type_item') {
					this.fileUploadShow = false;
					await this.addTypeChangeFunc(e.value[0]);
					this.$nextTick(() => {
						this.fileUploadShow = true;
					});
				}
				if (type == 'project_item') {
					await this.projectChangeFunc();
				}
			}
			this.close();
		},
		addTypeChangeFunc(item) {
			this.formData = {
				type_item: item,
				project_item: '',
				signing_company_item: '',
				contract_commencement_date: '',
				contract_completion_date: '',
				contract_duration_days: '',
				signing_date: '',
				contract_price: '',
				down_payment: '',
				progress_payment: '',
				balance_payment: '',
				system_quotation: '',
				discount_amount: '',
				earnest_money_contract_item: '',
				paid_amount: '',
				remark: '',
				contract_file: [],
				quotation_file: [],
				profit_statement_file: [],
				cost_list_file: []
			};
			this.dataObj = {};
			this.$nextTick(() => {
				this.selectProjectList(item.id);
			});
		},
		projectChangeFunc() {
			// 获取主体
			let companyList = this.companyList[0];
			let project_item = this.formData.project_item;
			this.formData.signing_company_item = companyList.find((item) => project_item.receiving_account_id == item.id);
			// 获取项目详情
			this.$Apipc
				.selectProjectDetails({
					project_id: project_item.id
				})
				.then((res) => {
					console.log(res, '项目详情');
					if (res.code == 200) {
						let data = res.data;
						this.dataObj = data;
						if (this.formData.type_item.id == 1) {
							let contract_price = (data.system_quotation - data.discount_amount).toFixed(2);
							this.formData.system_quotation = data.system_quotation;
							this.formData.discount_amount = data.discount_amount;
							this.formData.contract_price = Number(contract_price);
						}
						this.formData.balance_payment = '';
						this.jsWkFunc();
					}
				});
		},
		// 尾款计算
		jsWkFunc() {
			if (this.formData.type_item.id != 1) return;
			let { down_payment, progress_payment, contract_price } = this.formData;
			let { survey_fees } = this.dataObj;
			if (down_payment && progress_payment && contract_price) {
				let addNumber = Number(progress_payment) + Number(down_payment) + Number(survey_fees);
				addNumber = addNumber.toFixed(2);
				let subNumber = (Number(contract_price) - Number(addNumber)).toFixed(2).replace(/(\.0+|0+)$/, '');
				this.formData.balance_payment = subNumber;
			} else {
				this.formData.balance_payment = '';
			}
		},

		// 时间计算
		dateChangeFunc() {
			// 日期处理
			if (this.formData.contract_commencement_date && this.formData.contract_completion_date) {
				const date1 = new Date(this.formData.contract_commencement_date);
				const date2 = new Date(this.formData.contract_completion_date);

				const oneDay = 24 * 60 * 60 * 1000; // 每天的毫秒数
				const firstTime = date1.getTime();
				const secondTime = date2.getTime();

				let contract_duration_days = Math.round(Math.abs((firstTime - secondTime) / oneDay));

				this.formData.contract_duration_days = contract_duration_days + 1;
			} else {
				this.formData.contract_duration_days = '';
			}
		},
		afterRead(files, type) {
			files.map((item) => {
				let obj = {
					url: item.url
				};
				this.formData[type].push(obj);
			});
		},
		deletePic(e, type) {
			console.log(e, type, 'deletePic');
			this.formData[type].splice(e.index, 1);
		},
		async submit() {
			let formData = this.formData;
			console.log(formData, 'sss');
			if (!formData.project_item) {
				this.$refs.uToast.show({
					message: '请选择项目名称'
				});
				return;
			}
			if (!formData.signing_company_item) {
				this.$refs.uToast.show({
					message: '请选择签约主体'
				});
				return;
			}
			if (formData.type_item.id == 1 || formData.type_item.id == 3) {
				if (!formData.contract_commencement_date) {
					this.$refs.uToast.show({
						message: '请选择合同开工日期'
					});
					return;
				}
				if (!formData.contract_completion_date) {
					this.$refs.uToast.show({
						message: '请选择合同完工日期'
					});
					return;
				}
			}
			if (!formData.signing_date) {
				this.$refs.uToast.show({
					message: '请选择合同签约日期'
				});
				return;
			}
			if (!formData.contract_price) {
				this.$refs.uToast.show({
					message: '请输入签约金额'
				});
				return;
			}
			if (formData.type_item.id == 1) {
				if (!formData.down_payment) {
					this.$refs.uToast.show({
						message: '请输入首期款金额'
					});
					return;
				}
				if (!formData.progress_payment) {
					this.$refs.uToast.show({
						message: '请输入进度款金额'
					});
					return;
				}
			}
			if (formData.contract_file.length == 0) {
				this.$refs.uToast.show({
					message: '请上传合同附件'
				});
				return;
			}
			if (formData.type_item.id == 1 && formData.quotation_file.length == 0) {
				this.$refs.uToast.show({
					message: '请上传报价单'
				});
				return;
			}
			if (formData.type_item.id == 1 && formData.profit_statement_file.length == 0) {
				this.$refs.uToast.show({
					message: '请上传利润单'
				});
				return;
			}
			if (formData.type_item.id == 1 && formData.cost_list_file.length == 0) {
				this.$refs.uToast.show({
					message: '请上传工程量清单'
				});
				return;
			}

			uni.showLoading({
				mask: true
			});

			let resImg = await this.$upload(formData.contract_file);
			let resImg1 = null;
			let resImg2 = null;
			let resImg3 = null;
			if (formData.quotation_file.length) {
				resImg1 = await this.$upload(formData.quotation_file);
			}
			if (formData.profit_statement_file.length) {
				resImg2 = await this.$upload(formData.profit_statement_file);
			}
			if (formData.cost_list_file.length) {
				resImg3 = await this.$upload(formData.cost_list_file);
			}
			let res = await this.$hApi.addContract({
				contract_type: formData.type_item.id,
				project_id: formData.project_item.id,
				contract_commencement_date: formData.contract_commencement_date || '',
				contract_completion_date: formData.contract_completion_date || '',
				contract_duration_days: formData.contract_duration_days || '',
				contract_price: formData.contract_price || '',
				down_payment: formData.down_payment || '',
				progress_payment: formData.progress_payment || '',
				balance_payment: formData.balance_payment || '',
				signing_company_id: formData.signing_company_item.id,
				signing_company_name: formData.signing_company_item.account_name,
				earnest_money_contract_id: formData.earnest_money_contract_item ? formData.earnest_money_contract_item.id : '',
				signing_date: formData.signing_date || '',
				remark: formData.remark || '',
				contract_file: resImg.arrResult,
				quotation_file: resImg1 ? resImg1.arrResult[0].file_url : '',
				profit_statement_file: resImg2 ? resImg2.arrResult[0].file_url : '',
				cost_list_file: resImg3 ? resImg3.arrResult[0].file_url : ''
			});

			uni.hideLoading();
			if (res.code == 200) {
				var pages = getCurrentPages();
				var perPage = pages[pages.length - 2];
				if (perPage && perPage.$vm.$refs.contractManagement) {
					perPage.$vm.$refs.contractManagement.searchFunc();
				}

				setTimeout(() => {
					if (pages[pages.length - 2]) {
						uni.navigateBack({
							delta: 1
						});
					} else {
						uni.reLaunch({
							url: '/pages/index/index'
						});
					}
				}, 500);
			}
			if (res.code == 6064) {
				this.yhShow = true;
				return;
			}
			uni.showToast({
				title: res.code == 200 ? '操作成功' : res.message,
				icon: res.code == 200 ? 'success' : 'error'
			});
		},

		yhSubmit() {
			let formData = this.formData;
			uni.reLaunch({
				url: `/pagesC/projectManagement/addDiscount/addDiscount?project_id=${formData.project_item.id}&project_name=${formData.project_item.project_name}&price=${formData.contract_price}`
			});
		},
		selectProjectList(type) {
			this.$Apipc
				.selectProjectList({
					less_status: [1150],
					greater_status: type == 1 ? [1095] : []
				})
				.then((res) => {
					console.log(res, '项目列表');
					if (res.code == 200) {
						this.projectList = [res.data];
					}
				});
		},
		getList() {
			// 签约主体
			this.$Apipc
				.getCompanyList({
					account_type: 1,
					page: 1,
					num: 999
				})
				.then((res) => {
					console.log(res, '主体列表');
					if (res.code == 200) {
						this.companyList = [res.data.list];
					}
				});
		}
	}
};
</script>

<style lang="scss" scoped></style>
